<?php

namespace App\Service\Index;

use App\Constants\ErrorCode;
use App\Exception\ApiException;
use App\Model\CallBase;
use App\Model\DiscountVideoUsers;
use App\Model\User;
use App\Model\UserBlacklist;
use App\Model\UserCoin;
use App\Model\UserProfile;
use App\Model\VideoCall;
use App\Model\VideoCallAuditConfig;
use App\Model\VoiceCall;
use App\Service\BaseService;
use App\Service\CallBaseService;
use App\Service\ServiceTrait\GetUserInfoTrait;
use Hyperf\Database\Model\Builder;
use Hyperf\Database\Model\Model;

class DiscountVideoCallService extends CallBaseService
{
    use GetUserInfoTrait;

    /**
     * 被拨打者的id
     * @var
     */
    private $womanUserId;

    /**
     * 被拨打者的资料
     * @var Builder|Model|object|null
     */
    private $hostProfile;

    /**
     * 主控制器
     * @return array
     */
    public function handle(): array
    {
        $this->userId = $this->getUserId();

        $this->womanUserId = $this->request->input('woman_user_id', 0);

        //不能打给自己
        if ($this->userId == $this->womanUserId) {
            throw new ApiException('不能拨打给自己~', ErrorCode::PARAMETER_ERROR);
        }

        //检测是不是客服账号
        if (User::checkOfficial($this->womanUserId)) {
            throw new ApiException('暂无法拨打给小助手~', ErrorCode::PARAMETER_ERROR);
        }

        $callFrom = CallBase::FROM_DISCOUNT_CALL;

        $this->checkCallAuthority(VideoCall::CALL_TYPE);

        //修改以前无效状态
        VideoCall::finishOldCall($this->userId);

        //添加通话记录
        VideoCall::addRecord($this->userId, $this->womanUserId, $callFrom, DiscountVideoUsers::DISCOUNT_COIN, 3);

        //呼叫回调
        $this->callHook($this->womanUserId, $this->userId, VideoCall::CALL_TYPE);
        $config = (new VideoCallAuditConfig())->getConfig($this->userId);
        $ret = [
            'permit'       => 1,
            'user_info'    => UserProfile::buildHostItem($this->womanUserId),
            'support_face' => User::checkFaceSupport($this->womanUserId),
            'jHConfig'     => $config
        ];

        log_user_result($this->userId, "discountVideo:womanUserId:{$this->womanUserId}==" . json_encode($ret));

        return $ret;
    }

    public function checkCallAuthority($callType = VoiceCall::CALL_TYPE)
    {
        //获取对方和自己资料信息
        $profile     = UserProfile::getProfile($this->womanUserId);
        $validAppIds = explode(',', env('CHAT_NO_LIMIT_APPID', 6));
        if ((!$profile || $profile->avatar_vrfy != 1) && !in_array($this->appId, $validAppIds)) {
            throw new ApiException('非认证状态，暂不可呼叫～', ErrorCode::PARAMETER_ERROR);
        }

        //拉黑关系
        $checkBlack = UserBlacklist::check($this->womanUserId, $this->userId);
        if ($checkBlack) {
            throw new ApiException('暂无法发起通话~', ErrorCode::CHAT_BLACK_LMT);
        }

        //对方是否允许接听，或者对方正在通话
        $permitField = $callType == VoiceCall::CALL_TYPE ? 'call_permit' : 'video_permit';
        if ($profile->{$permitField} == 0) {
            throw new ApiException('对方忙或手机不在身边，请稍后再试', ErrorCode::HOST_BUSY);
        }

        $callCls = $callType == VoiceCall::CALL_TYPE ? VoiceCall::class : VideoCall::class;
        //对方是否在打语音电话
        if (
            VoiceCall::checkUserChatting($this->womanUserId) ||
            VideoCall::checkUserChatting($this->womanUserId)
        ) {
            throw new ApiException('对方忙或手机不在身边，请稍后再试', ErrorCode::HOST_BUSY);
        }

        // 判断对方用户状态
        $user = User::getUser($this->womanUserId);
        if ($user && $user->status != User::STATUS_OK) {
            throw new ApiException('对方暂无法接听', ErrorCode::DEFAULT_ERROR);
        }

        //个人虚拟币账户信息
        $userCoin = UserCoin::getUserInfo($this->userId);
        //账户不够
        if (!$userCoin || $userCoin['total_coin'] < DiscountVideoUsers::DISCOUNT_COIN) {
            return $this->setError(ErrorCode::COIN_NOT_ENOUGH, '你的余额不足，请充值后再试~');
        }
    }
}
